package com.smily.excel;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * POI生成EXCEL文件
 * Created by Smily on 10/17/15.
 */
public class PoiExpExcel {

    public static void main(String[] args){
        //创建EXCEL工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个工作表
        HSSFSheet sheet = workbook.createSheet();
        //创建表头数据
        String[] title = {"id", "name", "sex"};
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = null;
        //插入表头
        for(int i = 0; i < title.length; i++){
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
        }
        //追加数据
        for (int i = 1; i < 10; i ++){
            HSSFRow nextRow = sheet.createRow(i);
            HSSFCell cell1 = nextRow.createCell(0);
            cell1.setCellValue("a" + i);
            cell1 = nextRow.createCell(1);
            cell1.setCellValue("user" + i);
            cell1 = nextRow.createCell(2);
            cell1.setCellValue("男");
        }

        //创建文件
        File file = new File("/Users/Smily/Documents/Coding/idae_output/poi_test.xls");
        try {
            file.createNewFile();
            FileOutputStream stream = FileUtils.openOutputStream(file);
            workbook.write(stream);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
